package com.spice.service.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spice.common.constant.PermissionConstant;
import com.spice.common.exception.SpiceException;
import com.spice.common.result.Response;
import com.spice.common.result.ResultCodeEnum;
import com.spice.common.util.CheckUtil;
import com.spice.common.util.PermissionUtil;
import com.spice.service.util.ShiroUtil;
import com.spice.service.entity.form.EditEntityForm;
import com.spice.service.entity.pojo.Authorization;
import com.spice.service.entity.pojo.User;
import com.spice.service.service.AuthorizationService;
import com.spice.service.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/authorization")
public class AuthorizationController {

    @Autowired
    UserService userService;
    @Autowired
    AuthorizationService authorizationService;

    @ApiOperation("获取目标用户权限信息")
    @GetMapping(value = "/getUserAuthorization/{userId}", produces = "application/json;charset=UTF-8")
    public Response getAllAuthorizations(@PathVariable("userId") String userId) {
        // 确认是否登录
        if (!ShiroUtil.isAuthenticated()) {
            return Response.setResult(ResultCodeEnum.NO_AUTHENTICATION);

        }
        // 确认权限
        if (!ShiroUtil.hasRoles(PermissionConstant.ROOT_ROLE)) {
            return Response.setResult(ResultCodeEnum.NO_PERMISSION);
        }
        // 确认目标用户是否存在
        if (userService.count(new LambdaQueryWrapper<User>()
                .eq(User::getId, userId)) == 0) {
            throw new SpiceException().message("目标用户不存在");
        }
        User user = userService.getById(userId);
        // 判断身份
        if (PermissionConstant.ROOT_ROLE.equals(user.getStatus())) {
            // 超级管理员
            return Response.ok()
                    .data("permission", PermissionUtil.getAllPermission())
                    .data("role", user.getStatus());
        } else if (PermissionConstant.PRODUCT_CENTER_DIRECTOR_ROLE.equals(user.getStatus())) {
            // 产品中心总监
            return Response.ok()
                    .data("permission", PermissionUtil.getProductCenterPermission())
                    .data("role", user.getStatus());
        } else if (PermissionConstant.QUALITY_CENTER_DIRECTOR_ROLE.equals(user.getStatus())) {
            // 质量中心总监
            return Response.ok()
                    .data("permission", PermissionUtil.getQualityCenterPermission())
                    .data("role", user.getStatus());
        } else if (PermissionConstant.PRODUCT_CENTER_WORKER_ROLE.equals(user.getStatus())
                || PermissionConstant.QUALITY_CENTER_WORKER_ROLE.equals(user.getStatus())) {
            // 产品中心专员、质量中心专员
            List<Authorization> authorizations = authorizationService.getBaseMapper()
                    .selectList(new LambdaQueryWrapper<Authorization>()
                            .eq(Authorization::getUserId, user.getId()));
            return Response.ok()
                    .data("permission", authorizations)
                    .data("role", user.getStatus());
        } else {
            return Response.ok()
                    .data("permission", "")
                    .data("role", user.getStatus());
        }


    }

    @ApiOperation("编辑用户权限信息(save,remove)")
    @PostMapping(value = "/editAuthorization/{method}", produces = "application/json;charset=UTF-8")
    public Response getAllUsers(@PathVariable("method") String method,
                                @RequestBody EditEntityForm<Authorization> editEntityForm) {

        // 判断是否登录
        if (!ShiroUtil.isAuthenticated()) {
            return Response.setResult(ResultCodeEnum.NO_AUTHENTICATION);
        }
        // 判断是否有权限
        if (!ShiroUtil.hasRoles(PermissionConstant.ROOT_ROLE)) {
            return Response.setResult(ResultCodeEnum.NO_PERMISSION);
        }
        // 判断是否有method参数
        if (CheckUtil.objectsHasNull(method)) {
            return Response.setResult(ResultCodeEnum.PARAM_LACK);
        }


        if ("save".equals(method)) {
            // 初始化参数
            Authorization newAuthorization = editEntityForm.getT().cleanup();
            // 确认该用户是否能拥有该权限

            // 确认该用户是否存在
            if (userService.count(new LambdaQueryWrapper<User>()
                    .eq(User::getId, newAuthorization.getUserId())) != 1) {
                throw new SpiceException().message("目标用户不存在");
            } else {
                User user = userService.getById(newAuthorization.getUserId());
                // 确认该用户身份
                if (!PermissionConstant.WORKER.equals(PermissionUtil.whichJob(user.getStatus()))) {
                    throw new SpiceException().message("该用户并非部门员工无法授权");
                }
                // 确认该用户属于哪个部门
                if (PermissionConstant.QUALITY_CENTER
                        .equals(PermissionUtil.whichDepartment(user.getStatus()))) {
                    // 质量中心
                    if (!PermissionUtil.isQualityCenterPermission
                            (newAuthorization.getPermission())) {
                        // 该权限不属于质量中心
                        throw new SpiceException().message("该权限不属于该用户部门，无法授权");
                    }
                } else if (PermissionConstant.PRODUCT_CENTER
                        .equals(PermissionUtil.whichDepartment(user.getStatus()))) {
                    // 产品中心
                    if (!PermissionUtil.isProductCenterPermission
                            (newAuthorization.getPermission())) {
                        // 该权限不属于产品中心
                        throw new SpiceException().message("该权限不属于该用户部门，无法授权");
                    }
                } else {
                    throw new SpiceException().message("该用户不属于任何部门，无法授权");
                }
            }
            // 至此，该权限允许赋予该用户

            // 该权限是否已经存在
            if (authorizationService.count(
                    new LambdaQueryWrapper<Authorization>()
                            .eq(Authorization::getUserId, newAuthorization.getUserId())
                            .eq(Authorization::getPermission, newAuthorization.getPermission())) == 0) {
                authorizationService.save(newAuthorization);
                return Response.ok()
                        .message("授予权限成功")
                        .data("authorities", authorizationService.getBaseMapper().selectList(
                                new LambdaQueryWrapper<Authorization>()
                                        .eq(Authorization::getUserId, newAuthorization.getUserId())));
            } else {
                throw new SpiceException().message("该用户已有该权限");
            }
        } else if ("remove".equals(method)) {
            // 初始化参数
            Long id = editEntityForm.getId();
            // 删除用户权限
            if (authorizationService.count(
                    new LambdaQueryWrapper<Authorization>()
                            .eq(Authorization::getId, id)) > 0) {
                String userId = authorizationService.getOne(new LambdaQueryWrapper<Authorization>()
                        .eq(Authorization::getId, id)).getUserId();
                authorizationService.removeById(id);
                return Response.ok()
                        .message("移除权限成功")
                        .data("authorities", authorizationService.getBaseMapper()
                                .selectList(new LambdaQueryWrapper<Authorization>()
                                        .eq(Authorization::getUserId, userId)));
            } else {
                throw new SpiceException().message("id不存在");
            }
        }
        return Response.ok().message("未执行任何操作");
    }

}
